/**
 * 搜索功能JavaScript
 * 实现文档搜索、结果展示等功能
 */

document.addEventListener('DOMContentLoaded', function() {
  console.log('搜索功能初始化开始');
  
  // 获取搜索相关元素
  const desktopSearchInput = document.getElementById('searchInput');
  const mobileSearchInput = document.getElementById('mobileSearchInput');
  const desktopSearchResults = document.getElementById('searchResults');
  const mobileSearchResults = document.getElementById('mobileSearchResults');
  const mobileSearchBtn = document.getElementById('mobileSearchBtn');
  const mobileSearchPanel = document.getElementById('mobileSearchPanel');
  const closeSearchBtn = document.getElementById('closeSearchBtn');
  
  console.log('桌面搜索框:', desktopSearchInput ? '已找到' : '未找到');
  console.log('桌面搜索结果容器:', desktopSearchResults ? '已找到' : '未找到');
  console.log('移动端搜索框:', mobileSearchInput ? '已找到' : '未找到');

  // 搜索防抖计时器
  let debounceTimer;
  
  // 注册搜索输入事件
  if (desktopSearchInput) {
    // 桌面搜索框输入事件
    desktopSearchInput.addEventListener('input', function(e) {
      const query = e.target.value.trim();
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => {
        handleSearch(query, desktopSearchResults);
      }, 300);
    });
    
    // 桌面搜索框焦点事件
    desktopSearchInput.addEventListener('focus', function() {
      if (this.value.trim()) {
        desktopSearchResults.style.display = 'block';
      }
    });
    
    // 确保桌面搜索框可见
    const desktopSearch = document.querySelector('.desktop-search');
    if (desktopSearch) {
      desktopSearch.classList.remove('hidden');
      desktopSearch.classList.add('flex');
    }
  } else {
    console.error('未找到桌面搜索框元素，搜索功能可能无法正常工作');
  }
  
  if (mobileSearchInput) {
    // 移动端搜索框输入事件
    mobileSearchInput.addEventListener('input', function(e) {
      const query = e.target.value.trim();
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => {
        handleSearch(query, mobileSearchResults);
      }, 300);
    });
  }
  
  // 移动端搜索按钮点击
  if (mobileSearchBtn) {
    mobileSearchBtn.addEventListener('click', function() {
      showMobileSearch();
    });
  }
  
  // 关闭移动端搜索面板
  if (closeSearchBtn) {
    closeSearchBtn.addEventListener('click', function() {
      hideMobileSearch();
    });
  }
  
  // 点击其他区域关闭搜索结果
  document.addEventListener('click', function(e) {
    if (desktopSearchResults && 
        e.target !== desktopSearchInput && 
        !desktopSearchResults.contains(e.target)) {
      desktopSearchResults.style.display = 'none';
    }
  });
  
  // ESC键关闭搜索结果和移动搜索面板
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
      if (desktopSearchResults) {
        desktopSearchResults.style.display = 'none';
      }
      hideMobileSearch();
    }
  });
  
  /**
   * 处理搜索请求
   * @param {string} query - 搜索关键词
   * @param {HTMLElement} resultsContainer - 结果容器
   */
  function handleSearch(query, resultsContainer) {
    if (!resultsContainer) return;
    
    if (!query) {
      resultsContainer.style.display = 'none';
      return;
    }
    
    // 显示加载状态
    resultsContainer.innerHTML = '<div class="p-4 text-center">搜索中...</div>';
    resultsContainer.style.display = 'block';
    
    // 调用搜索API
    fetch(`/api/search?q=${encodeURIComponent(query)}`)
      .then(response => response.json())
      .then(data => {
        updateSearchResults(data.results, query, resultsContainer);
      })
      .catch(error => {
        resultsContainer.innerHTML = '<div class="search-no-results">搜索出错，请重试</div>';
        console.error('搜索失败:', error);
      });
  }
  
  /**
   * 更新搜索结果
   * @param {Array} results - 搜索结果数组
   * @param {string} query - 搜索关键词
   * @param {HTMLElement} container - 结果容器
   */
  function updateSearchResults(results, query, container) {
    if (!container) return;
    
    if (results.length === 0) {
      container.innerHTML = `<div class="search-no-results">没有找到与 "${query}" 相关的结果</div>`;
      return;
    }
    
    let html = '';
    results.forEach(result => {
      html += `
        <a href="${result.path}" class="search-result-item">
          <div class="search-result-title">${result.title}</div>
          <div class="search-result-preview">${result.preview}</div>
        </a>
      `;
    });
    
    container.innerHTML = html;
    
    // 点击搜索结果项后隐藏搜索面板（移动端）
    const resultItems = container.querySelectorAll('.search-result-item');
    resultItems.forEach(item => {
      item.addEventListener('click', function() {
        hideMobileSearch();
      });
    });
  }
  
  /**
   * 显示移动端搜索面板
   */
  function showMobileSearch() {
    if (mobileSearchPanel) {
      mobileSearchPanel.classList.remove('hidden');
      mobileSearchPanel.style.transform = 'translateY(0)';
      
      // 聚焦搜索框
      setTimeout(() => {
        if (mobileSearchInput) {
          mobileSearchInput.focus();
        }
      }, 300);
      
      // 禁止背景滚动
      document.body.style.overflow = 'hidden';
    }
  }
  
  /**
   * 隐藏移动端搜索面板
   */
  function hideMobileSearch() {
    if (mobileSearchPanel) {
      mobileSearchPanel.style.transform = 'translateY(100%)';
      setTimeout(() => {
        mobileSearchPanel.classList.add('hidden');
        // 恢复背景滚动
        document.body.style.overflow = '';
      }, 300);
    }
  }
}); 